//
//  registerView.m
//  garbageclient
//
//  Created by Wang Wu on 11-9-15.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "registerView.h"
#import "commondef.h"
#import "RegexKitLite.h"

@implementation registerView

@synthesize delegate;

- (void)dealloc
{
    [navBar release];
    [namelabel release];
    [maillabel release];
    [nametext release];
    [mailtext release];
    [backbtn release];
    [registerbtn release];
    [super dealloc];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        CGRect screenrc = [[UIScreen mainScreen] applicationFrame];
        
        navBar = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, screenrc.size.width, NAV_HEIGHT)];
        
        [self addSubview: navBar];
        
        UINavigationItem *navItem = [[UINavigationItem alloc] initWithTitle: @"注册"];
        [navBar pushNavigationItem:navItem animated:YES];
        
        [navItem release];
        
        namelabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, NAV_HEIGHT, 100.0f, 60.0f)];
        namelabel.text = @"用户名";
        [self addSubview:namelabel];
        
        maillabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, NAV_HEIGHT + 60.0f, 100.0f, 60.0f)];
        maillabel.text = @"密码";
        [self addSubview:maillabel];
        
        nametext = [[UITextField alloc] initWithFrame:CGRectMake(100.0f, NAV_HEIGHT, 
                                                                 screenrc.size.width - 100.0f, 
                                                                 60.0f)];
        nametext.delegate = self;
        [self addSubview:nametext];
        
        mailtext = [[UITextField alloc] initWithFrame:CGRectMake(100.0f, NAV_HEIGHT + 60.0f, 
                                                               screenrc.size.width - 100.0f, 
                                                               60.0f)];
        mailtext.delegate = self;
        [self addSubview:mailtext];
        
        backbtn = [[UIButton alloc] initWithFrame:CGRectMake(100.0f, NAV_HEIGHT + 120.0f, 
                                                              100.0f, 60.0f)];
        [backbtn setTitle:@"返回" forState:UIControlStateNormal];
        [backbtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [backbtn addTarget:self action:@selector(backclick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:backbtn];
        
        registerbtn = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, NAV_HEIGHT + 120.0f, 
                                                                 100.0f, 60.0f)];
        [registerbtn setTitle:@"注册" forState:UIControlStateNormal];
        [registerbtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [registerbtn addTarget:self action:@selector(registerclick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:registerbtn];
        
        webdatabuf = [[NSMutableData alloc] initWithLength:0];

    }
    return self;
}

#pragma mark-textDelegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [nametext resignFirstResponder];
    [mailtext resignFirstResponder];
    return YES;
}


#pragma mark-button click
-(void)registerclick:(id)sender
{
    if ([nametext.text length] == 0) 
    {
        UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Alert" 
                                                          message:@"用户名不可为空" 
                                                         delegate:self
                                                cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [myAlert show];
    }
    else if([mailtext.text length] == 0)
    {
        UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Alert" 
                                                          message:@"邮箱不可为空" 
                                                         delegate:self
                                                cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [myAlert show];
    }
    else if([mailtext.text isMatchedByRegex:@"\\b([a-zA-Z0-9%_.+\\-]+)@([a-zA-Z0-9.\\-]+?\\.[a-zA-Z]{2,6})\\b"] == NO)
    {
        UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"Alert" 
                                                          message:@"邮箱格式不正确" 
                                                         delegate:self
                                                cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [myAlert show];
    }
    else
    {
        // 指定提交的URL地址
        NSString *str = @"http://www.mwinphone.com/wp-login.php?action=register";
        
        NSURL *url = [NSURL URLWithString:str];
        // 创建NSMutableURLRequest
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
        // 设置HTTP头信息
        [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        // 根据REST协议指定HTTPMethod为POST
        [request setHTTPMethod:@"POST"];
        // 将要提交的数据转换成JSON格式后设置为HTTPBody
        str = [[NSString alloc] initWithFormat:@"user_login=%@&user_email=%@",nametext.text,mailtext.text];
        [request setHTTPBody:[str dataUsingEncoding:NSUTF8StringEncoding]];
        // 定义HTTP将要返回的Response对象
        connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    }
}

-(void)backclick:(id)sender
{
    [delegate registerback];
}

#pragma mark-alertdelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.title == @"恭喜")
    {
        [delegate registerback];
    }
    
    [alertView release];
}

#pragma mark- connect
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
    [webdatabuf appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)aConn
{
    [connection release];
    
	NSString *jsonString = [[[NSString alloc] initWithData:webdatabuf encoding:NSUTF8StringEncoding] autorelease];
    NSRange r = [jsonString rangeOfString:@"login_error"];
    if(r.location == NSNotFound)
    {
        UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"恭喜" 
                                                          message:@"注册成功，请到邮箱取密码登陆" 
                                                         delegate:self
                                                cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [myAlert show];
    }
    else
    {
        jsonString = [jsonString substringFromIndex:[jsonString rangeOfString:@"login_error"].location];
        jsonString = [jsonString substringToIndex:[jsonString rangeOfString:@"<br />"].location];
        jsonString = [jsonString substringFromIndex:[jsonString rangeOfString:@"："].location + 1];
        
        UIAlertView *myAlert = [[UIAlertView alloc] initWithTitle:@"警告" 
                                                          message:jsonString 
                                                         delegate:self
                                                cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [myAlert show]; 
        nametext.text = @"";
        [nametext becomeFirstResponder];
    }
    
    [webdatabuf release];
    webdatabuf = [[NSMutableData alloc] initWithLength:0];
}
@end
